/*
 * @Author: ls
 * @Date: 2021-11-11 10:12:55
 * @LastEditTime: 2021-11-25 09:42:49
 * @LastEditors: ls
 * @Description: 打开本地图片
 * index.html 内添加img标签
 * <input id="OpenImageFile" type="file" capture="camera" accept="image/*" style="visibility: hidden">
 * @FilePath: \demo\assets\Script\OpenImageFile.ts
 */

export default class OpenImageFile {
	/**
	 * 能否重复上传
	 * @returns
	 */
	private static canRepeatUpload() {
		let input_imageFile = document.getElementById('OpenImageFile');
		if (input_imageFile == null) {
			console.error('上传失败！！！');
			return;
		}

		if (input_imageFile.outerHTML) input_imageFile.outerHTML = input_imageFile.outerHTML;

		// @ts-ignore
		if (input_imageFile.value) input_imageFile.value = null;
	}

	/**
	 * 打开文件操作
	 */
	public static openFile(cb) {
		let input_imageFile = document.getElementById('OpenImageFile');
		if (input_imageFile == null) return;

		// 添加需要处理的代码
		input_imageFile.onchange = function (event) {
			// @ts-ignore
			let files = event.target.files;
			let upType = files[0].type;
			if (upType == 'image/gif' || upType.indexOf('image') < 0) {
				alert('只允许上传图片文件！！！');
				OpenImageFile.canRepeatUpload();
				return;
			}

			if (files && files.length > 0) {
				try {
					if (window.FileReader) {
						var fileReader = new FileReader();
						/**将文件读取为DataURL */
						fileReader.readAsDataURL(files[0]);
						// 限制允许上传的图片最大为5m
						if (files[0].size > 1024 * 1024 * 5) {
							alert('文件过大，请重新选择！！！');
							OpenImageFile.canRepeatUpload();
							return;
						}
						/**成功读取 */
						fileReader.onload = function (e) {
							// 读取图片的操作
							if (fileReader.readyState == fileReader.DONE) {
								OpenImageFile.canRepeatUpload();
								let strImg = e.target.result;

								cb && cb(strImg);
							}
						};
					} else {
						alert('不支持你的浏览器！！！');
					}
				} catch (e) {
					alert('文件读取失败，请再试一次！！！');
					OpenImageFile.canRepeatUpload();
					return;
				}
			}
		};

		input_imageFile.click();
	}
}
